import datetime
import sys, time, os, signal
import numpy as np
from PIL import Image, ImageDraw
import cv2
from vncdotool import api


def record(output, host, port):
    print("Start Recording")
    pid = 0
    retval = 0
    cli = api.connect(host+"::"+port)
    cli.refreshScreen(False)
    try:
        def sigint_handler(sig, frame):
            raise KeyboardInterrupt

        signal.signal(signal.SIGINT, sigint_handler)

        cli.refreshScreen()
        cli.captureScreen(output)

    except KeyboardInterrupt:
        pass
    if pid:
        os.killpg(os.getpgid(pid), signal.SIGTERM)

    return retval


def main(args):
    # python3 vnc2mp4.py output.mp4 host:port fps password[OPTIONAL]
    if len(args) < 3:
        print("Missing parameters")
        sys.exit()
    else:
        output = args[0]
        host = args[1]
        port = args[2]
        # fps = args[2]
        # password = None
        # if len(args) == 4: password = args[3]
    record(output=output, host=host, port=port)

if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))
